package com.sdyeda.dtu.fx;

import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.sdyeda.dtu.DtuServerApplication;
import com.sdyeda.dtu.net.Server;

import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;

public class Tray {
	
	public Tray() {
		Init();
	}

	
	public void Init() {
		if(!SystemTray.isSupported()) {
			return;
		}
		
		TrayIcon trayicon = new TrayIcon(Toolkit.getDefaultToolkit()
				.getImage(getClass().getResource("/icon.png"))
				.getScaledInstance(16, 16, 0), "尾矿库DTU数据自动采集系统");
		
		PopupMenu menu = new PopupMenu();
		MenuItem open = new MenuItem("打开主界面");
		//MenuItemBorder 
		MenuItem exit = new MenuItem("退出");
	
		menu.add(open);
		menu.add(new MenuItem("-"));
		menu.add(exit);
		
		trayicon.setPopupMenu(menu);
		
		open.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				Platform.runLater(()->{
					Stage stage = DtuServerApplication.primarystage;
					//System.out.println(stage);
					if(stage!=null) {
						stage.show();
						stage.toFront();
					}
				});
			}
		});
		
		exit.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				Platform.runLater(() -> {
					TextInputDialog dialog = new TextInputDialog();
					dialog.setContentText("密码");
					dialog.setHeaderText("请输入密码");
					dialog.setTitle("请输入密码");
					dialog.showAndWait();
					//System.out.print(dialog.getResult());
					//System.out.print(Server.getPassword());
					if(!Server.getPassword().equals(dialog.getResult())){
						new Alert(AlertType.ERROR,"密码错误").show();
					}
					else {
						Platform.exit();//
						System.exit(0);
					}
				});
				//
			}
		});
		
		
		trayicon.addActionListener(listener ->{
			Platform.runLater(()->{
				Stage stage = DtuServerApplication.primarystage;
				//System.out.println(stage);
				if(stage!=null) {
					stage.show();
					stage.toFront();
				}
			});
		});
		
		try {
			SystemTray.getSystemTray().add(trayicon);
		} catch (AWTException e) {
			//e.printStackTrace();
		}
	
	}
}
